<?php

class sfApplyApplyForm extends sfGuardUserProfileForm
{
  private $validate = null;

  public function configure()
  {
    parent::configure();

    // We're making a new user or editing the user who is
    // logged in. In neither case is it appropriate for
    // the user to get to pick an existing userid. The user
    // also doesn't get to modify the validate field which
    // is part of how their account is verified by email.

    unset($this['user_id'], $this['validate']);

    // Add username and password fields which we'll manage
    // on our own. Before you ask, I experimented with separately
    // emitting, merging or embedding a form subclassed from
    // sfGuardUser. It was vastly more work in every instance.
    // You have to clobber all of the other fields (you can
    // automate that, but still). If you use embedForm you realize
    // you've got a nested form that looks like a
    // nested form and an end user looking at that and
    // saying "why?" If you use mergeForm you can't save(). And if
    // you output the forms consecutively you have to manage your
    // own transactions. Adding two fields to the profile form
    // is definitely simpler.


//    echo 'ERROES'.array_pop($this->getErrorSchema()->getErrors());
     $this->setWidget('soy', new sfWidgetFormChoice(array(
    'choices' => array('Hombre', 'Mujer'),)));
    $this->setWidget('busco', new sfWidgetFormChoice(array(
    'choices' => array('Mujer', 'Hombre'),)));

    $this->setWidget('username', new sfWidgetFormInput(
      array(), array('maxlength' => 16)
    ));

    
    $this->setWidget('password', new sfWidgetFormInputPassword(
      array(), array('maxlength' => 128)
    ));
    $this->widgetSchema->moveField('soy', sfWidgetFormSchema::FIRST);
    $this->widgetSchema->moveField('busco', sfWidgetFormSchema::AFTER, 'soy');
    $this->widgetSchema->moveField('username', sfWidgetFormSchema::AFTER, 'busco');
    $this->widgetSchema->moveField('password', sfWidgetFormSchema::AFTER, 'username');
    $this->widgetSchema->moveField('email', sfWidgetFormSchema::AFTER, 'password');
    $this->setWidget('is_mayor_edad',
            new sfWidgetFormInputCheckbox(array('default' => true)));
    $this->setWidget('is_quiero_recibir',
            new sfWidgetFormInputCheckbox(array('default' => false)));

//    $this->validatorSchema['is_mayor_edad'] = new sfValidatorBoolean(array(
//       'required' => false,
//       'true_values' => array('Y'),
//       'false_values' => array('N')));
//    $this->validatorSchema['is_quiero_recibir'] = new sfValidatorBoolean(array(
//       'required' => false,
//       'true_values' => array('Y'),
//       'false_values' => array('N')));
//    $this->setWidget('password2', new sfWidgetFormInputPassword(
//      array(), array('maxlength' => 128)
//    ));

//    $this->widgetSchema->moveField('password2', sfWidgetFormSchema::AFTER, 'password');

//    $this->widgetSchema->setLabels(array('password2' => 'Confirm Password'));

//    $email = $this->getWidget('email');
//    $class = get_class($email);
//    $this->setWidget('email2', new $class(
//      array(), array('maxlength' => $email->getAttribute('maxlength'))
//    ));

//    $this->widgetSchema->moveField('email2', sfWidgetFormSchema::AFTER, 'email');

//    $this->widgetSchema->setLabels(array(
//      'fullname' => 'Full Name',
//      'email2' => 'Confirm Email'
//    ));

    $this->widgetSchema->setNameFormat('sfApplyApply[%s]');
    $this->widgetSchema->setFormFormatterName('list');

//    $errorRowFormat = "<div 'style=color:red'>something</div>";
//$this->getWidgetSchema()->getFormFormatter()->setErrorListFormatInARow($errorRowFormat);


    // We have the right to an opinion on these fields because we
    // implement at least part of their behavior. Validators for the
    // rest of the user profile come from the schema and from the
    // developer's form subclass
    $this->setValidator('soy',new sfValidatorString());
    $this->setValidator('busco',new sfValidatorString());

    $this->setValidator('username',
      new sfValidatorAnd(array(
        new sfValidatorString(array(
          'required' => true,
          'trim' => true,
          'min_length' => 4,
          'max_length' => 16
        ),array('required'=>'Es necesario un nombre de usuario'
            ,'min_length'=>'El Nombre de usuario debe ser como minimo de %min_length% letras'
            ,'max_length'=>'El Nombre de usuario debe ser como maximo de %max_length% letras'
            )),
        // Usernames should be safe to output without escaping and generally username-like.
        new sfValidatorRegex(array(
          'pattern' => '/^\w+$/'
        ), array('invalid' => 'Solo puede contener letras, numeros y underscores.')),
        new sfValidatorDoctrineUnique(array(
          'model' => 'sfGuardUser',
          'column' => 'username'
        ), array('invalid' => 'Este Usuario ya esta siendo usando.'))
      ))
    );

    // Passwords are never printed - ever - except in the context of Symfony form validation which has built-in escaping.
    // So we don't need a regex here to limit what is allowed

    // Don't print passwords when complaining about inadequate length
    $this->setValidator('password', new sfValidatorString(array(
      'required' => true,
      'trim' => true,
      'min_length' => 6,
      'max_length' => 128
    ),array('min_length' => 'La contraseña debe tener como minimo %min_length% caracteres.'
        ,'required'=>'Es necesaria una contraseña.'
        ,'max_length'=>'La contraseña debe ser como maximo de %max_length% letras')));

//    $this->setValidator('password2', new sfValidatorString(array(
//      'required' => true,
//      'trim' => true,
//      'min_length' => 6,
//      'max_length' => 128
//    ), array(
//      'min_length' => 'That password is too short. It must contain a minimum of %min_length% characters.')));

    // Be aware that sfValidatorEmail doesn't guarantee a string that is preescaped for HTML purposes.
    // If you choose to echo the user's email address somewhere, make sure you escape entities.
    // <, > and & are rare but not forbidden due to the "quoted string in the local part" form of email address
    // (read the RFC if you don't believe me...).

    $this->setValidator('email', new sfValidatorAnd(array(
      new sfValidatorEmail(array('required' => true, 'trim' => true), 
              array('invalid' => 'Formato de email Inválido.'
                  ,'required' => 'Es necesario un mail.')),
      new sfValidatorString(array('required' => true, 'max_length' => 80)),
      new sfValidatorDoctrineUnique(array(
        'model' => 'sfGuardUserProfile',
        'column' => 'email'
      ), array('invalid' => 'Ya hay un usuario registrado con ese mail.'))
    )));
    $this->setValidator('is_mayor_edad',new sfValidatorString(array('required' => true)
            ,array('required' => 'Debe aceptar los terminos y condiciones.')));
    $this->setValidator('is_quiero_recibir',new sfValidatorBoolean());

//    $this->setValidator('email2', new sfValidatorEmail(array(
//      'required' => true,
//      'trim' => true
//    )));

    // Disallow <, >, & and | in full names. We forbid | because
    // it is part of our preferred microformat for lists of disambiguated
    // full names in sfGuard apps: Full Name (username) | Full Name (username) | Full Name (username)
//    $this->setValidator('fullname', new sfValidatorAnd(array(
//      new sfValidatorString(array(
//        'required' => true,
//        'trim' => true,
//        'min_length' => 6,
//        'max_length' => 128)),
//        new sfValidatorRegex(array(
//          'pattern' => '/^[^<>&\|]+$/',
//        ), array('invalid' => 'Full names may not contain &lt;, &gt;, | or &amp;.'))
//    )));

    $schema = $this->validatorSchema;

    // Hey Fabien, adding more postvalidators is kinda verbose!
    $postValidator = $schema->getPostValidator();

//    $postValidators = array(
//      new sfValidatorSchemaCompare(
//        'password',
//        sfValidatorSchemaCompare::EQUAL,
//        'password',
//        array(),
//        array('invalid' => 'The passwords did not match.')
//      ),
//      new sfValidatorSchemaCompare(
//        'email',
//        sfValidatorSchemaCompare::EQUAL,
//        'email',
//        array(),
//        array('invalid' => 'The email addresses did not match.')
//      )
//    );

    if ($postValidator)
    {
      $postValidators[] = $postValidator;
//      $postValidators['soy'] = new sfValidatorString();

    }
//
    $this->validatorSchema->setPostValidator(new sfValidatorAnd($postValidators));
  }

  public function setValidate($validate)
  {
    $this->validate = $validate;
  }

  public function doSave($con = null){
    $soy=array('Hombre','Mujer');
    $busco=array('Mujer','Hombre');
    $user = new sfGuardUser();
    $user->setUsername($this->getValue('username'));
    $user->setPassword($this->getValue('password'));
    $user->setEmailAddress($this->getValue('email'));
    $user->setSoy($soy[$this->getValue('soy')]);

    $user->setBusco($busco[$this->getValue('busco')]);
    $user->setIsMayorEdad($this->getValue('is_mayor_edad'));
    $user->setIsQuieroRecibir($this->getValue('is_quiero_recibir'));
    // They must confirm their account first
    $user->setIsActive(false);
    $user->save();
    $this->userId = $user->getId();
    return parent::doSave($con);
  }

  public function updateObject($values = null)
  {
    $object = parent::updateObject($values);
    $object->setUserId($this->userId);
    $object->setValidate($this->validate);

    // Don't break subclasses!
    return $object;
  }
}

